package com.shirley.pers.zhufengfmvi;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shirley.pers.zhufengfmvi.adapters.AlbumDetailAdapter;
import com.shirley.pers.zhufengfmvi.customViews.CircleImageView;
import com.shirley.pers.zhufengfmvi.entities.AlbumsDetailAlbum;
import com.shirley.pers.zhufengfmvi.entities.AlbumsDetailTracks;
import com.shirley.pers.zhufengfmvi.tasks.AlbumsDetailTask;
import com.shirley.pers.zhufengfmvi.tasks.TaskCallback;
import com.shirley.pers.zhufengfmvi.tasks.TaskResult;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AlbumsDetailActivity extends AppCompatActivity implements TaskCallback, View.OnClickListener {
    private static final String TAG = AlbumsDetailActivity.class.getSimpleName();
    private boolean isScrollStateFinish = false;
    //页号
    private long pageNum = 1;
    //分页
    private long pageSize = 20;
    //专辑id
    private long mAlbumId = -1;
    //是否升序排列
    private boolean isAsc = true;
    //曲目id
    private long mTrackId = -1;

    private ImageView mBackImageView;
    private TextView mTitleTextView;
    private ImageView mCoverLargeImageView;
    private TextView mPlayTimesTextView;
    private CircleImageView mAvatarPathImageView;
    private TextView mNickNameTextView;
    private TextView mIntroTextView;
    private ListView mListView;
    private ImageView mPlayTagImageView;
    private ImageView mRightIndicatorTagImageView;

    private AlbumDetailAdapter mAdapter;
    private ExecutorService service;
    private AlbumsDetailTracks albumsDetailTracks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_albums_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.albums_detail_list_toolBar);
        setSupportActionBar(toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayShowTitleEnabled(false);
            supportActionBar.setDefaultDisplayHomeAsUpEnabled(false);
        }
        //初始化控件
        initView();
        //设置事件监听
        setComponentListener();

        Intent intent = getIntent();

        //专辑Id
        mAlbumId = intent.getLongExtra(Constants.EXTRA_ALBUM_ID, -1);
        //曲目Id
        mTrackId = intent.getLongExtra(Constants.EXTRA_TRACK_ID, -1);

        if (mAlbumId != -1 && mTrackId != -1) {
            AlbumsDetailTask task = new AlbumsDetailTask(this, pageNum, pageSize, mAlbumId, isAsc);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                service = Executors.newFixedThreadPool(2);
                task.executeOnExecutor(service);
            } else {
                task.execute();
            }
            //TODO:检测当前的网络状态

            //开启服务，播放音乐()
//            Intent service = new Intent(this, PlayService.class);
//            service.putExtra(Constants.EXTRA_ALBUM_ID, mAlbumId);
//            service.putExtra(Constants.EXTRA_ALBUM_ID, mTrackId);
//            startService(service);
        }
    }

    /**
     * 事件监听
     */
    private void setComponentListener() {
        mBackImageView.setOnClickListener(this);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mBackImageView = (ImageView) findViewById(R.id.albums_detail_list_back);
        mTitleTextView = (TextView) findViewById(R.id.albums_detail_list_title);
        mCoverLargeImageView = (ImageView) findViewById(R.id.albums_detail_list_coverLarge);
        mPlayTimesTextView = (TextView) findViewById(R.id.albums_detail_list_playTimes);
        mAvatarPathImageView = (CircleImageView) findViewById(R.id.albums_detail_list_avatarPath);
        mNickNameTextView = (TextView) findViewById(R.id.albums_detail_list_nickname);
        mIntroTextView = (TextView) findViewById(R.id.albums_detail_list_intro);

        mPlayTagImageView = (ImageView) findViewById(R.id.album_detail_play);
        mRightIndicatorTagImageView = (ImageView) findViewById(R.id.album_detail_right_indicators);
    }

    @Override
    public void onTaskFinished(TaskResult result) {
        if (result != null) {
            switch (result.state) {
                case 0:
                    Object data = result.data;
                    if (data instanceof JSONObject) {
                        JSONObject jsonObject = (JSONObject) data;
                        try {
                            //获取专辑信息
                            JSONObject albumJo = jsonObject.getJSONObject("album");
                            AlbumsDetailAlbum albumsDetailAlbum = new AlbumsDetailAlbum();
                            albumsDetailAlbum.parseJson(albumJo);

                            //设置数据
                            String coverLargeUrl = albumsDetailAlbum.getCoverLarge();
                            if (coverLargeUrl != null) {
                                Picasso.with(this).load(coverLargeUrl).into(mCoverLargeImageView);
                                mPlayTagImageView.setVisibility(View.VISIBLE);
                            }
                            String avatarPath = albumsDetailAlbum.getAvatarPath();
                            if (avatarPath != null) {
                                Picasso.with(this).load(avatarPath).into(mAvatarPathImageView);
                            }

                            mTitleTextView.setText(albumsDetailAlbum.getTitle());
                            mPlayTimesTextView.setText(Long.toString(albumsDetailAlbum.getPlayTimes()));
                            mNickNameTextView.setText(albumsDetailAlbum.getNickname());
                            mIntroTextView.setText(albumsDetailAlbum.getIntro());
                            mRightIndicatorTagImageView.setVisibility(View.VISIBLE);

                            //获取曲目列表信息
                            JSONObject tracksJo = jsonObject.getJSONObject("tracks");
                            albumsDetailTracks = new AlbumsDetailTracks();
                            albumsDetailTracks.parseJson(tracksJo);

                            mListView = (ListView) findViewById(R.id.albums_detail_list);
                            assert mListView != null;
                            mListView.setOnScrollListener(new OnListViewScrollListener());
                            View headView = LayoutInflater.from(this).inflate(R.layout.item_function_album_detail_list, null);
                            //集数
                            TextView itemNum = (TextView) headView.findViewById(R.id.album_detail_list_function_item_num);
                            //订阅
                            View subscripationView = headView.findViewById(R.id.album_detail_list_function_subscription);
                            //批量下载
                            View downloadView = headView.findViewById(R.id.album_detail_list_function_download);
                            //相关推荐
                            View recommendView = headView.findViewById(R.id.album_detail_list_function_recommend);
                            //选集
                            View chooseItemView = headView.findViewById(R.id.album_detail_list_function_choose_item);
                            //排序
                            View sortView = headView.findViewById(R.id.album_detail_list_function_sort);

                            itemNum.setText("共" + Long.toString(albumsDetailTracks.getTotalCount()) + "集");
                            //TODO:相关功能的点击操作
                            mListView.addHeaderView(headView, null, true);

                            mAdapter = new AlbumDetailAdapter(this, albumsDetailTracks);
                            mListView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 8:
                    //Snackbar.make(new Snackbar.SnackbarLayout(this), "网络异常", Snackbar.LENGTH_LONG).show();
                    Toast.makeText(this, "网络异常", Toast.LENGTH_LONG).show();
                    break;
                case 9:
                    //Snackbar.make(new Snackbar.SnackbarLayout(this), "服务器数据解析异常", Snackbar.LENGTH_LONG).show();
                    Toast.makeText(this, "服务器数据解析异常", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.albums_detail_list_back:
                finish();
                break;
        }
    }

    /**
     * ListView 的滑动点击事件
     */
    private class OnListViewScrollListener implements AbsListView.OnScrollListener {
        private View footerViewFlush;

        /**
         * Callback method to be invoked while the list view or grid view is being scrolled. If the
         * view is being scrolled, this method will be called before the next frame of the scroll is
         * rendered. In particular, it will be called before any calls to
         * {@link Adapter#getView(int, View, ViewGroup)}.
         *
         * @param view        The view whose scroll state is being reported
         * @param scrollState The current scroll state. One of
         *                    {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}.
         */
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            Log.i(TAG, "onScrollStateChanged: scrollState:" + scrollState);
            //停止滑动
            if (scrollState == SCROLL_STATE_FLING) {
                isScrollStateFinish = true;
            } else {
                isScrollStateFinish = false;
            }
        }

        /**
         * Callback method to be invoked when the list or grid has been scrolled. This will be
         * called after the scroll has completed
         *
         * @param view             The view whose scroll state is being reported
         * @param firstVisibleItem the index of the first visible cell (ignore if
         *                         visibleItemCount == 0)
         * @param visibleItemCount the number of visible cells
         * @param totalItemCount   the number of items in the list adaptor
         */
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            Log.i(TAG, "onScroll: firstVisibleItem:" + firstVisibleItem + ",visibleItemCount:" + visibleItemCount + ",totalItemCount:" + totalItemCount);
            Log.i(TAG, "onScroll: firstVisibleItem+visibleItemCount)==totalItemCount:" + ((firstVisibleItem + visibleItemCount) == totalItemCount));
            Log.i(TAG, "onScroll: isScrollStateFinish:" + isScrollStateFinish);

            //滑倒最底部
            if ((firstVisibleItem + visibleItemCount) == totalItemCount && isScrollStateFinish) {
                //分页查询
                //没有加载完所有的数据
                if (albumsDetailTracks.getTotalCount() != albumsDetailTracks.getList().size()) {
                    //添加刷新界面
                    if (mListView.getFooterViewsCount()==0){
                        footerViewFlush = View.inflate(AlbumsDetailActivity.this, R.layout.item_footer_album_detail_list, null);
                        ImageView loadingIv = (ImageView) footerViewFlush.findViewById(R.id.iv_loding_animation);
                        AnimationDrawable drawable = (AnimationDrawable) loadingIv.getDrawable();
                        drawable.start();
                        mListView.addFooterView(footerViewFlush);
                    }

                    pageNum += 1;
                    AlbumsDetailTask task = new AlbumsDetailTask(new TaskCallback() {
                        @Override
                        public void onTaskFinished(TaskResult result) {

                            if (result != null) {
                                switch (result.state) {
                                    case 0:
                                        Object data = result.data;
                                        if (data instanceof JSONObject) {
                                            JSONObject jsonObject = (JSONObject) data;
                                            try {
                                                mListView.removeFooterView(footerViewFlush);
                                                //获取曲目列表信息
                                                JSONObject tracksJo = jsonObject.getJSONObject("tracks");
                                                AlbumsDetailTracks albumsDetailTracks = new AlbumsDetailTracks();
                                                albumsDetailTracks.parseJson(tracksJo);

                                                AlbumsDetailActivity.this.albumsDetailTracks.getList().addAll(albumsDetailTracks.getList());
                                                mAdapter.notifyDataSetChanged();

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                        break;
                                    case 8:
                                        //Snackbar.make(new Snackbar.SnackbarLayout(this), "网络异常", Snackbar.LENGTH_LONG).show();
                                        Toast.makeText(AlbumsDetailActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                                        break;
                                    case 9:
                                        //Snackbar.make(new Snackbar.SnackbarLayout(this), "服务器数据解析异常", Snackbar.LENGTH_LONG).show();
                                        Toast.makeText(AlbumsDetailActivity.this, "服务器数据解析异常", Toast.LENGTH_LONG).show();
                                        break;
                                }
                            }

                        }
                    }, pageNum, pageSize, mAlbumId, isAsc);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        task.executeOnExecutor(service);
                    } else {
                        task.execute();
                    }
                } else {

                    if (mListView.getFooterViewsCount() == 0) {
                        View footerView = View.inflate(AlbumsDetailActivity.this, R.layout.item_footer_album_detail_list, null);
                        ImageView loadingIv = (ImageView) footerView.findViewById(R.id.iv_loding_animation);
                        loadingIv.setVisibility(View.GONE);
                        TextView textShow = (TextView) footerView.findViewById(R.id.iv_loding_text);
                        textShow.setText("数据加载完毕，共" + albumsDetailTracks.getList().size() + "条数据");
                        mListView.addFooterView(footerView);
                        AnimationDrawable drawable = (AnimationDrawable) loadingIv.getDrawable();
                        drawable.start();
                    }
                }
            }
        }
    }
}
